document.addEventListener('DOMContentLoaded', async () => {
    const blogList = document.querySelector('.blog-list');
    const createPostBtn = document.getElementById('createPostBtn');
    const prevButton = document.getElementById('prevPage');
    const nextButton = document.getElementById('nextPage');

    let currentPage = 1;
    let totalPages = 1;
    const pageSize = 10;

    // 检查登录状态并控制创建帖子按钮的显示
    function checkLoginStatus() {
        const token = localStorage.getItem('accessToken');
        if (token) {
            createPostBtn.style.display = 'flex';
        } else {
            createPostBtn.style.display = 'none';
        }
    }

    // 创建帖子按钮点击事件
    createPostBtn.addEventListener('click', () => {
        const token = localStorage.getItem('accessToken');
        if (token) {
            window.location.href = 'create-post.html';
        } else {
            Swal.fire({
                icon: 'warning',
                title: '请先登录',
                text: '创建帖子需要登录账号',
                confirmButtonText: '去登录',
                confirmButtonColor: '#546d9e',
                showCancelButton: true,
                cancelButtonText: '取消'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = 'login.html';
                }
            });
        }
    });

    // 初始检查登录状态
    checkLoginStatus();

    // 渲染文章卡片
    function renderPost(post) {
        const storedViews = sessionStorage.getItem(`post_${post.id}_views`);
        const storedLikes = sessionStorage.getItem(`post_${post.id}_likes`);

        const views = storedViews ? parseInt(storedViews) : (post.views || 0);
        const likes = storedLikes ? parseInt(storedLikes) : (post.likes || 0);

        return `
            <div class="blog-card" onclick="window.location.href='post-detail.html?id=${post.id}'">
                ${post.cover ? `
                    <div class="blog-card-cover">
                        <img src="${post.cover}" alt="${post.title}">
                    </div>
                ` : ''}
                <div class="blog-card-content-wrapper">
                    <div>
                        <div class="blog-card-header">
                            <h2>${post.title}</h2>
                        </div>
                        <div class="blog-card-content">
                            <p>${post.content.substring(0, 150)}...</p>
                        </div>
                    </div>
                    <div class="blog-card-footer">
                        <span>
                            <i class="fas fa-user"></i>
                            ${post.user ? (post.user.nickname || post.user.username) : '未知'}
                        </span>
                        <span>
                            <i class="far fa-calendar"></i>
                            ${new Date(post.createTime).toLocaleDateString()}
                        </span>
                        <span>
                            <i class="far fa-eye"></i>
                            ${views}
                        </span>
                        <span>
                            <i class="far fa-heart"></i>
                            ${likes}
                        </span>
                    </div>
                </div>
            </div>
        `;
    }

    function renderPageNumbers(current, total) {
        const pageNumbers = document.querySelector('.page-numbers');
        let html = '';

        function addPageNumber(num) {
            return `<button class="page-number ${num === current ? 'active' : ''}" 
                            data-page="${num}">${num}</button>`;
        }

        if (total <= 7) {
            for (let i = 1; i <= total; i++) {
                html += addPageNumber(i);
            }
        } else {
            // 始终显示第一页
            html += addPageNumber(1);

            //  根据当前页位置显示页码 设total = 10
            if (current <= 4) {
                // 当前页靠近开始  
                for (let i = 2; i <= 5; i++) {
                    html += addPageNumber(i); // 1 2 3 4 5 ... 10
                }
                html += '<span class="dots">...</span>';
                html += addPageNumber(total);
            } else if (current >= total - 3) {
                // 当前页靠近结束
                html += '<span class="dots">...</span>';
                for (let i = total - 4; i <= total; i++) {
                    html += addPageNumber(i); // 1 ... 6 7 8 9 10
                }
            } else {
                // 当前页在中间
                html += '<span class="dots">...</span>';
                for (let i = current - 2; i <= current + 2; i++) {
                    html += addPageNumber(i); // 1 ... 3 4 5 6 7 ... 10
                }
                html += '<span class="dots">...</span>';
                html += addPageNumber(total);
            }
        }

        pageNumbers.innerHTML = html;

        // 页码点击事件
        document.querySelectorAll('.page-number').forEach(button => {
            button.addEventListener('click', async () => {
                const pageNum = parseInt(button.dataset.page);
                if (pageNum !== current) {
                    button.style.transform = 'scale(0.95)';
                    setTimeout(() => {
                        button.style.transform = 'scale(1)';
                    }, 100);

                    await loadPosts(pageNum);
                }
            });
        });
    }

    // 加载文章列表
    async function loadPosts(page) {
        try {
            // 显示加载动画
            const loadingHtml = Array(5).fill().map(() => `
                <div class="blog-card blog-loading-item"></div>
            `).join('');

            requestAnimationFrame(() => {
                blogList.innerHTML = loadingHtml;
            });

            const response = await request.get('/post/page', {
                params: {
                    page: page - 1,
                    size: pageSize,
                    status: 1
                }
            });

            console.log('API Response:', response);

            const posts = response.data;

            if (!posts.content || posts.content.length === 0) {
                blogList.innerHTML = `
                    <div class="no-posts">
                        <span>还没有文章，快去创建第一篇文章吧！</span>
                    </div>`;
                return;
            }

            currentPage = page;
            totalPages = posts.totalPages;

            const newContent = posts.content.map(post => renderPost(post)).join('');
            requestAnimationFrame(() => {
                blogList.innerHTML = newContent;
                prevButton.disabled = currentPage === 1;
                nextButton.disabled = currentPage === totalPages;
                renderPageNumbers(currentPage, totalPages);
            });

        } catch (error) {
            console.error('获取文章列表失败：', error);
            blogList.innerHTML = `
                <div class="error-message">
                    <span>服务器异常，请稍后重试</span>
                </div>`;
        }
    }

    prevButton.addEventListener('click', () => {
        if (currentPage > 1) {
            loadPosts(currentPage - 1);
        }
    });

    nextButton.addEventListener('click', () => {
        if (currentPage < totalPages) {
            loadPosts(currentPage + 1);
        }
    });

    // 初始加载
    await loadPosts(1);
}); 